package helper

import (
	"log"

	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
)

type ValidateFuncMap map[string]validator.Func

var (
	trans ut.Translator
)

func InitValidator(vfm ValidateFuncMap) {
	translator := zh.New()

	trans, _ = ut.New(translator, translator).GetTranslator("zh")

	var (
		validate *validator.Validate
		ok       bool
	)

	//注册自定义验证方法
	for fname, f := range vfm {
		if validate, ok = binding.Validator.Engine().(*validator.Validate); ok {
			validate.RegisterValidation(fname, f)
		} else {
			log.Fatalf("validate RegisterValidation %v fail", fname)
		}
	}

	_ = zhTranslations.RegisterDefaultTranslations(validate, trans)
}

func Translate(err error) string {
	var result string
	errors, ok := err.(validator.ValidationErrors)
	if !ok {
		return err.Error()
	}
	for _, err := range errors {
		// tag   := err.Tag()   //绑定的验证方法
		// field := err.Field() //绑定的验证字段
		msg := err.Translate(trans) + ";"
		result += msg
	}
	return result
}
